package com.twq.func.ctrldef

import java.io.{File, PrintWriter}

/**
 * Created by tangweiqun on 2017/11/29.
 */
object ControlStructureDef {
  def main(args: Array[String]): Unit = {

    //1、定义一个"twice"的控制结构
    //重复一个操作两次，然后返回结果
    def twice(op: Double => Double, x: Double) = op(op(x))

    twice(_ + 1, 5)
    //twice((x:Double)=>x+1,5)

    //2、常见的控制结构：打开一个资源，然后操作这个资源，最后关闭这个资源
    def withPrintWriter(file: File, op: PrintWriter => Unit) = {
      val writer = new PrintWriter(file)
      try {
        op(writer)
      } finally {
        writer.close()
      }
    }

    withPrintWriter(
      new File("date.txt"),
      writer => writer.println(new java.util.Date)
    )

    withPrintWriter(
      new File("date.txt"),
      writer => {
        println("writing some information to file")
        writer.println(s"${new java.util.Date()} Hello")
        println("writed some in information to file")
      }
    )

    //3、使得客户端使用我们自定义的控制结构更像内置的控制结构
    def withPrintWriterWithCurry(file: File)(op: PrintWriter => Unit) = {
      val writer = new PrintWriter(file)
      try {
        op(writer)
      } finally {
        writer.close()
      }
    }

    val file = new File("date.txt")
    withPrintWriterWithCurry(file) { writer =>
      writer.println(new java.util.Date)
    }

  }


  def printDate(file: File): Unit = {
    val writer = new PrintWriter(file)
    try {
      writer.println(new java.util.Date())
    } finally {
      writer.close()
    }
  }

  def printHelloWithLog(file: File): Unit = {
    val writer = new PrintWriter(file)
    try {
      println("writing some information to file")
      writer.println(s"${new java.util.Date()} Hello")
      println("writed some in information to file")
    } finally {
      writer.close()
    }
  }

  var i = 10
  while (i == 0) {
    i -= 1
    println(i)
  }

  until(i == 0) {
    i -= 1
    println(i)
  }

  def until(condition: => Boolean)(block: => Unit) {
    if (!condition) {
      block
      until(condition)(block)
    }
  }
}
